package com.hs.service.impl;

import com.hs.entity.Course;
import com.hs.entity.CourseCollect;
import com.hs.entity.User;
import com.hs.mapper.CourseCollectMapper;
import com.hs.mapper.CourseMapper;
import com.hs.mapper.UserMapper;
import com.hs.service.CourseCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class CourseCollectServiceImpl implements CourseCollectService {
    @Autowired
    private CourseCollectMapper courseCollectMapper;

    @Override
    public int addCourseCollect(CourseCollect courseCollect) {
        return courseCollectMapper.addCourseCollect(courseCollect);
    }

    @Override
    public int updateCourseCollect(CourseCollect courseCollect) {
        return courseCollectMapper.updateCourseCollect(courseCollect);
    }

    @Override
    public int deleteCourseCollect(int id) {
        return courseCollectMapper.deleteCourseCollect(id);
    }

    @Override
    public List<CourseCollect> getCourseCollectById(int id) {
        return courseCollectMapper.getCourseCollectById(id);
    }
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    // 保证事务一致性
    public int collectCourse(int cid, int uid) {
        // 先检查是否已收藏
        int i = courseCollectMapper.add(cid,uid);
        // 收藏后，需要给当前的用户增加积分
        User user = userMapper.getUserById(uid);
        int points = user.getPoint()+10;
        userMapper.updatePointsById(uid,points);
        Course course = courseMapper.getCourseByid(cid);
        course.setCollectCount(course.getCollectCount()+1);
        courseMapper.updateCourse(course);
        return i;
    }
    @Override
    public int cancelCollect(int cid, int uid) {
        int i = courseCollectMapper.delete(cid,uid);
        // 收藏后，需要给当前的用户增加积分
        User user = userMapper.getUserById(uid);
        int points = user.getPoint()-10;
        userMapper.updatePointsById(uid,points);
        Course course = courseMapper.getCourseByid(cid);
        course.setCollectCount(course.getCollectCount()-1);
        courseMapper.updateCourse(course);
        return i;
    }

    @Override
    public boolean isCollected(int cid, int uid) {
        Integer count = courseCollectMapper.checkCollect(cid, uid);
        return count != null && count > 0;
    }

}
